﻿using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Coldairarrow.Util.ERQcde
{
    public class XcxERQcdes
    {
        public static string GetAccessToken(string appId, string scret)
        {
            string token = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + scret);
            Newtonsoft.Json.Linq.JObject _jObject = Newtonsoft.Json.Linq.JObject.Parse(token);
            var value = _jObject["access_token"].ToString();
            return value;
        }

        public static string GetGzhSign(string appId, string scret)
        {
            Log.Information("=======进入获取accentToken22222=======");
            var value = "";
            string token = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + scret);
            Newtonsoft.Json.Linq.JObject _jObject = Newtonsoft.Json.Linq.JObject.Parse(token);
            Log.Information("=>获取AToken errorcode=" + _jObject.ToJson().ToString());
            if (_jObject["errcode"].IsNullOrEmpty())
            {
                var accessToken = _jObject["access_token"].ToString();
                Log.Information("=======获取accentToken成功=======");
                string sign = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi");
                Newtonsoft.Json.Linq.JObject _jObject1 = Newtonsoft.Json.Linq.JObject.Parse(sign);
                Log.Information("=>获取签名 errorcode=" + _jObject1.ToJson().ToString());
                if (_jObject1["errcode"].ToString() == "0" && _jObject1["errmsg"].ToString() == "ok")
                {
                    Log.Information("=======获取签名成功=======");
                    value = _jObject1["ticket"].ToString();
                }
            }

            
            return value;
        }

        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Information("=>Get获取失败 ex=" + ex.Message);
                throw;
            }
            finally
            {
                request = null;
                response = null;
            };

            return responseStr;
        }

        /// <summary>
        /// 生成小程序二维码
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="scene">参数（32位内）</param>
        /// <param name="page">小程序页面路径</param>
        /// <param name="width">二维码大小</param>
        /// <param name="appid">小程序appId</param>
        /// <param name="secret">小程序密钥</param>
        /// <returns></returns>
        public static string GetXcxQRCodeHelper(string path, string scene, string page, string width, string appid, string secret)
        {
            string imStr = "";
            try
            {
                string token = GetAccessToken(appid, secret);
                string _url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
                string strUrl = _url;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strUrl);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                string options = string.Empty;
                options = "{";
                options += string.Format("\"scene\":\"{0}\",", scene);
                options += string.Format("\"page\":\"{0}\",", page);
                options += string.Format("\"width\":\"{0}\"", width);
                //options += string.Format("\"is_hyaline\":\"{0}\",", "false");
                //options += string.Format("\"auto_color\":\"{0}\",", "false");
                //options += "\"line_color\":{";
                //options += string.Format("\"r\":\"{0}\",","0");
                //options += string.Format("\"b\":\"{0}\",","0");
                //options += string.Format("\"g\":\"{0}\"","0");
                //options += "}";
                options += "}";

                byte[] playload;
                playload = System.Text.Encoding.UTF8.GetBytes(options);
                request.ContentLength = playload.Length;
                System.IO.Stream writer = request.GetRequestStream();
                writer.Write(playload, 0, playload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();

                byte[] val = StreamToBytes(s);

                if (response.ContentType.Contains("application/json"))
                {
                    string res = Encoding.UTF8.GetString(val);
                }

                System.IO.File.WriteAllBytes(path, val);
                s.Dispose();
                writer.Dispose();
            }
            catch(Exception ex)
            {
                return "";
            }

            return imStr;
        }

        public static byte[] StreamToBytes(System.IO.Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }

            return bytes.ToArray();
        }

    }
    
}
